package com.cnzha.mr.mapTable;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhaoxin
 * @email: zdkk@foxmail.com
 * @Date: 2020/4/5 22:35
 */
public class TableMapper extends Mapper<LongWritable, Text, Text, NullWritable> {

    private String tableName;
    TableBean bean = new TableBean();
    Text k = new Text();
    Map pdMap = new HashMap();


    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        URI[] cacheFiles = context.getCacheFiles();
        String path = cacheFiles[0].getPath();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
        String line;
        while (StringUtils.isNotEmpty(line = bufferedReader.readLine())) {
            String[] fields = line.split("\t");
            // 3 缓存数据到集合
            pdMap.put(fields[0], fields[1]);
        }
        bufferedReader.close();

    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 1 获取输入数据
        String line = value.toString();

        String[] fields = line.split("\t");
        String pid = fields[1];

        // 2.2 封装bean对象
        bean.setId(fields[0]);
        bean.setpId(pid);
        bean.setAmount(Integer.parseInt(fields[2]));
        bean.setpName((String) pdMap.get(pid));
        bean.setTableName("order");

        k.set(bean.toString());
        // 3 写出
        context.write(k, NullWritable.get());

    }
}
